/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import Facade.CurrencyFacadeLocal;
import entity.CurrencyEE;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJBException;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.validator.ValidatorException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.persistence.NoResultException;

/**
 *
 * @author Vojtisek
 */
public class CurrencyConverter implements Converter {

    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        try {
            if (value==null) {
                return null;
            }
            CurrencyEE currencyEE = lookupCurrencyFacadeBean().find(value);
            return currencyEE;
        } catch (EJBException ex) {
            Logger.getLogger(CurrencyConverter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoResultException ex) {
            Logger.getLogger(CurrencyConverter.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(CurrencyConverter.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public String getAsString(
            FacesContext context, UIComponent component, Object value) {
        return value.toString();

    }

    private CurrencyFacadeLocal lookupCurrencyFacadeBean() {
        try {
            Context c = new InitialContext();
            return (CurrencyFacadeLocal) c.lookup("java:comp/env/CurrencyFacadeBean");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
}
